package com.yanliang.handler;

import com.yanliang.model.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * @author yanliang
 * @date 5/23/20202:31 PM
 */
@Slf4j
public class UserServerHandler extends ChannelInboundHandlerAdapter {
	private ApplicationContext applicationContext;

	public UserServerHandler(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		RpcRequest rpcRequest = (RpcRequest) msg;
		Object result = null;
		try {
			String className = rpcRequest.getClassName();
			String methodName = rpcRequest.getMethodName();
			Class clazz = Class.forName(className);
			Object obj = applicationContext.getBean(clazz);

			Method method = clazz.getMethod(methodName, rpcRequest.getParameterTypes());
			result = method.invoke(obj, rpcRequest.getParameters());
		} catch (Exception e) {
			log.error("调用{}类的{}方法{}时发生错误，参数为{}，错误原因{}", rpcRequest.getClassName(),
					rpcRequest.getMethodName(), rpcRequest.getParameters(), e.getMessage());
		} finally {
			ctx.writeAndFlush(result);
		}

	}
}
